<template>
	<view class="order-detail-page" v-if="orderLoaded && order">
		<!-- 1. 顶部状态和倒计时 -->
		<view class="header-status">
			<view class="status-line">
				<text class="status-text">{{ orderStatusText }}</text>
				<!-- 如果订单状态是待支付 -->
				<uni-icons v-if="order.status === 'pending_payment'" 
						   :type="showCountdown ? 'arrowup' : 'arrowdown'" 
						   size="18" color="#333" @click="toggleCountdownVisibility"></uni-icons>
			</view>
			<!-- 倒计时区域，仅在待支付且显示时可见 -->
			<view class="countdown-timer" v-if="order.status === 'pending_payment' && showCountdown && countdown && countdown.timeLeft > 0">
				<text>{{ countdown.message }}</text>
				<text class="time-segment">{{ countdown.hours }}</text>时
				<text class="time-segment">{{ countdown.minutes }}</text>分
				<text class="time-segment">{{ countdown.seconds }}</text>秒内未付款，订单将自动关闭
			</view>
             <view class="status-message" v-else-if="order.status === 'pending_payment' && showCountdown && countdown && countdown.timeLeft <= 0">
                 订单支付超时，已自动关闭
             </view>
		</view>

		<!-- 2. 地址信息 -->
		<view class="address-section card-style" v-if="order.address">
			<uni-icons type="location-filled" size="20" color="#666" class="location-icon"></uni-icons>
			<view class="address-details">
				<view class="contact-info">
					<text class="name">{{ order.address.name }}</text>
					<text class="phone">{{ order.address.phone }}</text>
				</view>
				<text class="full-address">{{ fullAddress }}</text>
			</view>
			<!-- 待支付状态下才可修改地址 -->
			<!-- <button v-if="order.status === 'pending_payment'" class="modify-address-btn" size="mini" @click="modifyAddress">修改地址</button> -->
		</view>

		<!-- 3. 商品信息 -->
		<view class="product-section card-style" v-if="order.product" @click="gotoProductDetail(order.product.id)">
			<image class="product-image" :src="firstProductImage" mode="aspectFill"></image>
			<view class="product-info">
				<text class="product-name">{{ order.product.title }}</text>
				<!-- 可以添加规格等信息 -->
			</view>
			<text class="product-price">¥{{ order.product.price ? order.product.price.toFixed(2) : '0.00' }}</text>
		</view>

		<!-- 4. 价格明细 -->
		<view class="price-details-section card-style">
			<view class="price-item">
				<text class="label">成交价</text>
				<uni-icons :type="showMorePriceDetails ? 'arrowup' : 'arrowdown'" size="16" color="#999" @click="togglePriceDetails"></uni-icons>
				<text class="value actual-price">¥{{ order.totalAmount ? order.totalAmount.toFixed(2) : '0.00' }}</text>
			</view>
			<view v-if="showMorePriceDetails">
				<view class="price-item">
					<text class="label">商品总价</text>
					<!-- JSON中没有productAmount字段，使用product.price -->
					<text class="value">¥{{ order.product && order.product.price ? order.product.price.toFixed(2) : '0.00' }}</text>
				</view>
				<view class="price-item">
					<text class="label">运费</text>
					<text class="value">¥{{ order.product && order.product.shippingFee ? order.product.shippingFee.toFixed(2) : '0.00' }}</text>
				</view>
				<!-- 可以添加优惠、积分抵扣等 -->
			</view>
		</view>
		
		<!-- 5. 订单信息 -->
		<view class="order-info-section card-style">
			<view class="info-item">
				<text class="label">订单编号</text>
				<text class="value">{{ order.id }}</text> <!-- 使用JSON返回的id作为订单编号 -->
				<button class="copy-btn" size="mini" @click="copyText(order.id)">复制</button>
			</view>
			<!-- <view class="info-item" @click="gotoTransactionDispute">
				<text class="label">交易快照</text>
				<text class="value placeholder">发生交易争议时，可作为判断依据</text>
				<uni-icons type="right" size="16" color="#C0C4CC"></uni-icons>
			</view> -->
			<view class="info-item" v-if="order.paymentSn">
				<text class="label">支付宝交易号</text>
				<text class="value">{{ order.paymentSn }}</text>
				<button class="copy-btn" size="mini" @click="copyText(order.paymentSn)">复制</button>
			</view>
			<view class="info-item" v-if="order.createDate">
				<text class="label">创建时间</text>
				<text class="value">{{ formatDateTime(order.createDate) }}</text> <!-- 使用JSON返回的createDate -->
			</view>
			<view v-if="showMoreOrderInfo">
				<view class="info-item" v-if="order.paymentTime">
					<text class="label">付款时间</text>
					<text class="value">{{ formatDateTime(order.paymentTime) }}</text>
				</view>
				<view class="info-item" v-if="order.shippingTime">
					<text class="label">发货时间</text>
					<text class="value">{{ formatDateTime(order.shippingTime) }}</text>
				</view>
				<view class="info-item" v-if="order.receiveTime">
					<text class="label">确认收货时间</text>
					<text class="value">{{ formatDateTime(order.receiveTime) }}</text>
				</view>
			</view>
			<!-- 仅当有更多信息可显示时才出现“查看更多” -->
			<view class="toggle-more-info" @click="toggleOrderInfoVisibility" v-if="hasMoreOrderInfoToShowComputed">
				<text>{{ showMoreOrderInfo ? '收起' : '查看更多' }}</text>
				<uni-icons :type="showMoreOrderInfo ? 'arrowup' : 'arrowdown'" size="16" color="#999"></uni-icons>
			</view>
		</view>

		<!-- 6. 卖家信息 -->
		<view class="seller-section card-style" v-if="userId !== order.userId && order.seller">
			<view class="seller-header">
				<text class="title">卖家信息</text>
			</view>
			<view class="seller-details">
				<image class="seller-avatar" :src="order.seller.sellerAvatar" mode="aspectFill"></image>
				<text class="seller-name">{{ order.seller.sellerName }}</text>
				<text class="seller-credit">信用：{{ order.seller.sellerCredit || '未知' }}</text>
			</view>
		</view>

		<view class="seller-section card-style" v-if="userId === order.userId">
			<view class="seller-header">
				<text class="title">买家信息</text>
			</view>
			<view class="seller-details">
				<image class="seller-avatar" :src="order.buyer.buyerAvatar" mode="aspectFill"></image>
				<text class="seller-name">{{ order.buyer.buyerName }}</text>
				<text class="seller-credit">信用：{{ order.buyer.buyerCredit || '未知' }}</text>
			</view>
		</view>


		<!-- 7. 为你推荐 (占位) -->
		<!-- <view class="recommendation-section">
			<view class="rec-title">
				<uni-icons type="heart-filled" color="#FF5000" size="20" style="margin-right: 8rpx;"></uni-icons>
				为你推荐
			</view>			
			<view class="rec-placeholder">--- 推荐商品区域 ---</view>
		</view> -->

		<!-- 8. 底部操作栏 -->
		<view class="bottom-actions" :style="{ paddingBottom: safeAreaInsetsBottom + 'px' }">
			<!-- <button class="action-btn secondary-btn" @click="contactSeller">
				<uni-icons type="chatbubble" size="18" color="#555" style="margin-right: 6rpx;"></uni-icons>
				联系卖家
			</button> -->
			<!-- 根据订单状态显示不同的操作按钮 -->
			<button v-if="order.status === 'pending_payment'" class="action-btn" @click="openCancelOrderDrawer">取消订单</button>
			<button v-if="order.status === 'pending_payment'" class="action-btn primary-btn" @click="goToPayment">去付款</button>

			<!-- <button v-if="order.status === 'paid'" class="action-btn" @click="viewLogistics">查看物流</button> -->
			<!-- 其他待发货状态按钮，如提醒发货 -->

			<!-- <button v-if="order.status === 'shipped'" class="action-btn" @click="viewLogistics">查看物流</button> -->
			<button v-if="order.status === 'shipped'" class="action-btn primary-btn" @click="gotoCompleted">确认收货</button>

			<!-- <button v-if="order.status === 'completed' && !order.isReviewed" class="action-btn" @click="rateOrder">评价订单</button> -->
			<!-- <button v-if="(order.status === 'completed' || order.status === 'closed' || order.status === 'cancelled')" class="action-btn" @click="buyAgain">再次租用</button> -->
            <!-- 已完成/已关闭/已取消状态下通常不再有主要操作按钮 -->
		</view>
		<!-- 底部安全区占位，防止内容被操作栏遮挡 -->
		<view :style="{ height: bottomBarHeight + 'px' }"></view>


		<!-- 取消订单原因抽屉 -->
		<uni-popup ref="cancelOrderDrawer" type="bottom" background-color="#fff">
			<view class="cancel-drawer-content">
				<text class="drawer-title">请选择取消订单原因</text>
				<radio-group @change="cancelReasonChange">
					<label v-for="(reason, index) in cancelReasons" :key="index" class="reason-item">
						<text>{{ reason.text }}</text>
						<radio :value="reason.value" :checked="reason.value === selectedCancelReason" color="#FFC800" style="transform:scale(0.8)" />
					</label>
				</radio-group>
				<view class="drawer-actions">
					<button class="drawer-btn secondary" @click="closeCancelOrderDrawer">暂不取消</button>
					<button class="drawer-btn primary" @click="confirmCancelOrder" :disabled="!selectedCancelReason">取消订单</button>
				</view>
				<view :style="{ height: safeAreaInsetsBottom + 'px' }"></view> <!-- 底部安全区 -->
			</view>
		</uni-popup>
		<!-- 加载中或加载失败提示 -->
		<view class="loading-mask" v-if="!orderLoaded">
			<text>{{ loadError ? '订单加载失败' : '加载中...' }}</text>
		</view>
	</view>
</template>

<script>
// 可能需要引入日期处理库，比如 dayjs (需要安装: npm install dayjs)
// import dayjs from 'dayjs'; // 或者使用其他日期处理方法
const app = getApp(); // 假设 app 是你的全局应用实例

export default {
	data() {
		return {
			order: null, // 订单数据初始化为 null
            orderLoaded: false, // 标记订单数据是否加载完成
            loadError: false, // 标记订单是否加载失败
			userId: '',
			countdown: { // 倒计时对象
				hours: '00',
				minutes: '00',
				seconds: '00',
                timeLeft: 0, // 剩余毫秒数
                message: '剩余' // 倒计时前缀文本
			},
			countdownInterval: null,
			showCountdown: true, // 是否显示倒计时
			showMorePriceDetails: false, // 是否显示更多价格明细
			showMoreOrderInfo: false, // 是否显示更多订单信息
			safeAreaInsetsBottom: 0, // 底部安全区高度
			bottomBarHeight: 0, // 底部操作栏实际高度 + 额外padding

			// 取消订单相关
			cancelReasons: [
				{ text: '我不想买了', value: '不想买了' },
				{ text: '信息填写错误，重新拍', value: '信息错误' },
				{ text: '卖家缺货', value: '卖家缺货' },
				{ text: '同城见面交易', value: '同城交易' },
				{ text: '其他原因', value: '其他' }
			],
			selectedCancelReason: '', // 选中的取消原因
		};
	},
	computed: {
		// 根据订单状态 code 返回状态文本
		orderStatusText() {
			if (!this.order || !this.order.status) return '加载中...';
			switch (this.order.status) {
				case 'pending_payment':
					if(this.userId === this.order.userId){
						return '请您尽快付款';
					}else{
						return '等待买家付款';
					}
				case 'paid': return '等待卖家发货';
				case 'shipped': return '卖家已发货';
				case 'completed': return '订单已完成';
				case 'closed': return '订单已关闭';
				case 'cancelled': return '订单已取消'; // JSON 示例没有这个状态，但代码有
				default: return '未知状态';
			}
		},
		// 拼接完整的地址
		fullAddress() {
			if (!this.order || !this.order.address) return '';
			const address = this.order.address;
			// JSON 结构提供了 province, city, district, street, detailAddress
			// 简单的拼接逻辑，确保字段存在且非空
			return `${address.province || ''}${address.city || ''}${address.district || ''}${address.street || ''}${address.detailAddress || ''}`;
		},
		// 获取第一个商品图片 URL
		firstProductImage() {
			if (!this.order || !this.order.product || !this.order.product.imageUrls) return '';
			const imageUrls = this.order.product.imageUrls.split(',');
			return imageUrls.length > 0 ? imageUrls[0].trim() : '';
		},
		// 判断是否有更多订单信息可显示 (JSON中有哪些字段就判断哪些)
		hasMoreOrderInfoToShowComputed() {
			if (!this.order) return false;
			return this.order.paymentTime || this.order.shippingTime || this.order.receiveTime;
		}
	},
	onLoad(options) {
		uni.setNavigationBarTitle({
			title: '订单详情'
		});
		let userInfo = uni.getStorageSync('userInfo')
		if(userInfo.id){
			this.userId = userInfo.id
		}

		const orderId = options.id;
		if (orderId) {
			this.loadOrderDetail(orderId);
		} else {
			uni.showToast({ title: '缺少订单ID', icon: 'none' });
			this.orderLoaded = true; // 标记加载完成但失败
            this.loadError = true;
		}

		const { safeAreaInsets } = uni.getSystemInfoSync();
		if (safeAreaInsets) {
			this.safeAreaInsetsBottom = safeAreaInsets.bottom;
		}

         // 监听从地址列表页返回时传递的选中地址事件
         uni.$on('selectedAddress', this.handleSelectedAddressReturn);
	},
	onReady() {
		// 获取底部操作栏实际高度，用于占位
		// 使用 $nextTick 确保元素已渲染
		this.$nextTick(() => {
            const query = uni.createSelectorQuery().in(this);
            query.select('.bottom-actions').boundingClientRect(data => {
              if (data && data.height) {
                this.bottomBarHeight = data.height + 10; // 加一点padding
              } else {
                 this.bottomBarHeight = 100; // 查询失败时给一个默认高度
              }
               console.log("Calculated bottomBarHeight:", this.bottomBarHeight);
            }).exec();
        });
	},
	onUnload() {
		// 页面卸载时清除倒计时和事件监听
		if (this.countdownInterval) {
			clearInterval(this.countdownInterval);
		}
        uni.$off('selectedAddress', this.handleSelectedAddressReturn);
	},
    // 如果页面使用了 keep-alive，可能需要在 onHide/onShow 中处理监听和倒计时
    onShow() {
        if (this.order && this.order.status === 'pending_payment' && this.countdown.timeLeft > 0) {
            this.startCountdown(); // 重新开始倒计时
        }
        uni.$on('selectedAddress', this.handleSelectedAddressReturn); // 重新监听
    },
    onHide() {
        if (this.countdownInterval) {
	        clearInterval(this.countdownInterval); // 暂停倒计时
	    }
         uni.$off('selectedAddress', this.handleSelectedAddressReturn); // 取消监听
    },
	methods: {
		// 加载订单详情
		loadOrderDetail(orderId) {
            this.orderLoaded = false;
            this.loadError = false;
            uni.showLoading({ title: '加载中...' });

			app.globalData.Request.post(app.globalData.ApiConstant.Order.info, {
				orderId: orderId
			}).then((res) => {
				console.log('loadOrderDetail success:', res);
				uni.hideLoading();
				if (res.success && res.data) {
					this.order = res.data;
                    this.orderLoaded = true;

					// 处理日期字符串为可用的日期对象或时间戳
					this.order.createDate = this.order.createDate ? new Date(this.order.createDate.replace(/-/g, '/')).getTime() : null; // iOS兼容
                    this.order.paymentTime = this.order.paymentTime ? new Date(this.order.paymentTime.replace(/-/g, '/')).getTime() : null;
                    this.order.shippingTime = this.order.shippingTime ? new Date(this.order.shippingTime.replace(/-/g, '/')).getTime() : null;
                    this.order.receiveTime = this.order.receiveTime ? new Date(this.order.receiveTime.replace(/-/g, '/')).getTime() : null;
					if (this.order.status === 'pending_payment' && this.order.createDate) {
						// 假设订单在创建后24小时过期
						this.order.paymentExpireTime = this.order.createDate + 24 * 60 * 60 * 1000;
						this.startCountdown();
					} else {
                         if (this.countdownInterval) clearInterval(this.countdownInterval);
                    }

				} else {
					uni.showToast({ title: res.message || '获取订单详情失败', icon: 'none' });
                    this.orderLoaded = true;
                    this.loadError = true;
				}
			}).catch((err) => {
				console.error('loadOrderDetail error:', err);
				uni.hideLoading();
				uni.showToast({ title: '加载订单详情失败', icon: 'none' });
                this.orderLoaded = true;
                this.loadError = true;
			});
		},

		// 格式化日期时间字符串或时间戳
		formatDateTime(timestamp) {
			if (!timestamp) return '';
			const date = new Date(timestamp);
			return date.toLocaleString();
		},
		// 启动倒计时
		startCountdown() {
			if (this.countdownInterval) clearInterval(this.countdownInterval);

			const update = () => {
				const now = Date.now();
				let timeLeft = this.order.paymentExpireTime - now;

                // 更新倒计时对象的timeLeft
                this.countdown.timeLeft = timeLeft;

				if (timeLeft <= 0) {
					this.countdown = { hours: '00', minutes: '00', seconds: '00', timeLeft: 0, message: '已超时' };
					clearInterval(this.countdownInterval);
					this.handleOrderTimeout(); // 处理超时逻辑
					return;
				}

                // 确保时间不会出现负数（虽然timeLeft <= 0已经处理了）
                timeLeft = Math.max(0, timeLeft);

				const hours = Math.floor(timeLeft / (1000 * 60 * 60));
				const minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
				const seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);

				this.countdown.hours = String(hours).padStart(2, '0');
				this.countdown.minutes = String(minutes).padStart(2, '0');
				this.countdown.seconds = String(seconds).padStart(2, '0');
                this.countdown.message = '剩余'; // 确保消息是剩余
			};

			update(); // 立即执行一次
			this.countdownInterval = setInterval(update, 1000);
		},
		// 处理订单超时
		handleOrderTimeout() {
			console.log("订单已超时");
			// uni.showToast({ title: '订单已超时自动关闭', icon: 'none', duration: 2000 }); // 移到status-message显示更友好
			// 自动更新订单状态为 closed
            // 注意：实际业务中，订单状态通常由后端自动更新，前端刷新数据即可
            // 这里为了演示前端效果，直接修改状态，实际应重新调用 loadOrderDetail
            if (this.order.status === 'pending_payment') {
                 this.order.status = 'closed'; // 模拟更新状态
                 // 建议重新加载订单详情: this.loadOrderDetail(this.order.id);
            }
		},
		// 切换倒计时显示
		toggleCountdownVisibility() {
			if (this.order && this.order.status === 'pending_payment') {
				this.showCountdown = !this.showCountdown;
			}
		},
		// 切换价格明细显示
		togglePriceDetails() {
			this.showMorePriceDetails = !this.showMorePriceDetails;
		},
		// 切换更多订单信息显示
		toggleOrderInfoVisibility() {
			this.showMoreOrderInfo = !this.showMoreOrderInfo;
		},
		// 复制文本
		copyText(text) {
            if (!text) {
                uni.showToast({ title: '内容为空', icon: 'none' });
                return;
            }
			uni.setClipboardData({
				data: String(text), // 确保是字符串
				success: () => {
					uni.showToast({ title: '复制成功', icon: 'none' });
				},
                fail: (err) => {
                    console.error('复制失败:', err);
                    uni.showToast({ title: '复制失败', icon: 'none' });
                }
			});
		},
		// 修改地址
		modifyAddress() {
			if (this.order && this.order.status === 'pending_payment') {
                 console.log('Navigating to AddressListPage for selection');
                 // 导航到地址列表页，并开启选择模式
                 uni.navigateTo({
                     url: '/pages/tb/my/addressList?isSelect=true&orderId=' + this.order.id
                 });
            }
		},
        // 处理从地址列表页返回时选中的地址
        handleSelectedAddressReturn(selectedAddress) {
             console.log('Received selected address from AddressListPage:', selectedAddress);
             // 收到选中的地址后，通常需要调用API更新订单的收货地址
             if (selectedAddress && this.order && this.order.id) {
                 uni.showLoading({ title: '更新地址中...' });
                 // 模拟API调用，实际请替换为你的更新订单地址接口
                 app.globalData.Request.post(app.globalData.ApiConstant.Order.updateAddress, {
                     orderId: this.order.id,
                     addressId: selectedAddress.id // 假设更新接口只需要地址ID
                     // 或者传递完整的地址信息，根据接口设计
                     // newAddress: selectedAddress
                 }, {showLoad : false}).then(res => {
                     uni.hideLoading();
                     console.log('Update address API response:', res);
                     if (res.success) {
                         uni.showToast({ title: '地址更新成功', icon: 'success' });
                         // 地址更新成功后，刷新订单详情以显示新地址
                         this.loadOrderDetail(this.order.id);
                     } else {
                         uni.showToast({ title: res.message || '地址更新失败', icon: 'none' });
                     }
                 }).catch(err => {
                     uni.hideLoading();
                     console.error('Update address API error:', err);
                     uni.showToast({ title: '地址更新失败', icon: 'none' });
                 });
             }
        },
		// 跳转到商品详情
		gotoProductDetail(productId) {
            if (!productId) return;
			uni.showToast({ title: '跳转商品详情: ' + productId, icon: 'none' });
			uni.navigateTo({ url: '/pages/tb/product/productDetail?id=' + productId });
			// uni.navigateTo({ url: '/pages/product/ProductDetail?id=' + productId });
		},
		// 跳转到交易快照
		gotoTransactionDispute() {
			uni.showToast({ title: '查看交易快照', icon: 'none' });
			// 实际跳转到交易快照页面
		},
		// 联系卖家
		contactSeller() {
            if (!this.order || !this.order.seller || !this.order.seller.sellerId) {
                 uni.showToast({ title: '无法获取卖家信息', icon: 'none' });
                 return;
            }
			uni.navigateTo({
				url: '/pages/tb/chat/chat?productId=' + this.order.productId
			})
			// uni.showToast({ title: '联系卖家: ' + this.order.seller.sellerName, icon: 'none' });
			// 实际跳转到聊天页面，需要传递卖家ID
			// uni.navigateTo({ url: '/pages/chat/ChatPage?sellerId=' + this.order.seller.sellerId });
		},
		// 打开取消订单抽屉
		openCancelOrderDrawer() {
			this.selectedCancelReason = ''; // 重置选择
			this.$refs.cancelOrderDrawer.open();
		},
		// 关闭取消订单抽屉
		closeCancelOrderDrawer() {
			this.$refs.cancelOrderDrawer.close();
		},
		// 取消原因改变时
		cancelReasonChange(e) {
			this.selectedCancelReason = e.detail.value;
            console.log('Selected cancel reason:', this.selectedCancelReason);
		},
		// 确认取消订单
		confirmCancelOrder() {
			if (!this.selectedCancelReason) {
				uni.showToast({ title: '请选择取消原因', icon: 'none' });
				return;
			}
            if (!this.order || !this.order.id) {
                 uni.showToast({ title: '订单信息有误', icon: 'none' });
                 return;
            }

			uni.showLoading({ title: '正在取消...' });
			// 模拟API调用，实际请替换为你的取消订单接口
            app.globalData.Request.post(app.globalData.ApiConstant.Order.cancel, {
                orderId: this.order.id,
                cancelReason: this.selectedCancelReason
            }, {showLoad : false}).then(res => {
                 uni.hideLoading();
                 console.log('Cancel order API response:', res);
                 if (res.success) {
                     uni.showToast({ title: '订单已取消', icon: 'success' });
                     // 取消成功后刷新订单详情，后端会更新状态
                     this.loadOrderDetail(this.order.id);
                     this.closeCancelOrderDrawer();
                 } else {
                     uni.showToast({ title: res.message || '取消失败', icon: 'none' });
                 }
            }).catch(err => {
                 uni.hideLoading();
                 console.error('Cancel order API error:', err);
                 uni.showToast({ title: '取消失败', icon: 'none' });
            });
		},
		// 去付款
		goToPayment() {
            if (!this.order || !this.order.id) {
                 uni.showToast({ title: '订单信息有误', icon: 'none' });
                 return;
            }
			uni.showLoading({ title: '正在调起支付...' });
			// 实际跳转到支付页面或调起支付SDK
            console.log('Navigating to payment for order:', this.order.id);
            // 模拟支付成功后回调 loadOrderDetail 刷新状态
            setTimeout(() => {
                uni.hideLoading();
				app.globalData.Request.post(app.globalData.ApiConstant.Order.confirmPay, {
					orderId: this.order.id
				}).then((res)=>{
					if(res.success){
						uni.showToast({ title: '付款成功！', icon: 'success', duration: 1500 });
						// 模拟支付成功后，重新加载订单详情，后端会更新状态和付款时间
						this.loadOrderDetail(this.order.id);
					}
				})
                
            }, 2000);
		},
		// 查看物流 (模拟)
		viewLogistics() {
             if (!this.order || !this.order.id) {
                 uni.showToast({ title: '订单信息有误', icon: 'none' });
                 return;
            }
            uni.showToast({ title: '查看物流', icon: 'none' });
            // 实际跳转到物流详情页
            // uni.navigateTo({ url: '/pages/order/LogisticsPage?orderId=' + this.order.id });
        },
		// 确认收货 (模拟)
		confirmReceipt() {
             if (!this.order || !this.order.id) {
                 uni.showToast({ title: '订单信息有误', icon: 'none' });
                 return;
            }
            uni.showModal({
                title: '确认收货',
                content: '请确认您已收到商品。确认收货后，订单将自动完成。',
                confirmColor: '#ff5000',
                success: (res) => {
                    if (res.confirm) {
                         uni.showLoading({ title: '确认中...' });
                         // 模拟API调用
                         app.globalData.Request.post(app.globalData.ApiConstant.Order.confirmReceipt, {
                             orderId: this.order.id
                         }, {showLoad : false}).then(res => {
                              uni.hideLoading();
                              if (res.success) {
                                  uni.showToast({ title: '确认收货成功', icon: 'success' });
                                  this.loadOrderDetail(this.order.id); // 刷新订单状态
                              } else {
                                  uni.showToast({ title: res.message || '确认收货失败', icon: 'none' });
                              }
                         }).catch(err => {
                              uni.hideLoading();
                              console.error('Confirm receipt API error:', err);
                              uni.showToast({ title: '确认收货失败', icon: 'none' });
                         });
                    }
                }
            });
        },
		// 评价订单 (模拟)
		rateOrder() {
             if (!this.order || !this.order.id) {
                 uni.showToast({ title: '订单信息有误', icon: 'none' });
                 return;
            }
            uni.showToast({ title: '评价订单', icon: 'none' });
            // 实际跳转到评价页面
            // uni.navigateTo({ url: '/pages/order/RateOrderPage?orderId=' + this.order.id });
        },
		// 再次租用 (模拟)
		buyAgain() {
             if (!this.order || !this.order.product || !this.order.product.id) {
                 uni.showToast({ title: '商品信息有误', icon: 'none' });
                 return;
            }
            uni.showToast({ title: '再次租用', icon: 'none' });
            // 实际跳转到商品详情页或购物车/直接创建新订单
            // uni.navigateTo({ url: '/pages/product/ProductDetail?id=' + this.order.product.id });
        },
		gotoShipping(){
			// 去发货
			let that = this
			uni.showModal({
				title: '提示',
				content: '确认发货吗',
				confirmText: '确定',
				cancelText: '取消',
				success: function (res) {
					if (res.confirm) {
						app.globalData.Request.post(app.globalData.ApiConstant.Order.confirmShipped, 
						{orderId: that.order.id}).then((res)=>{
							if(res.success){
								uni.showToast({ title: '操作成功', icon: 'success' });
								setTimeout(() => {
									that.loadOrderDetail(that.order.id)
								}, 500);
							}else{
								uni.showToast({ title: '操作失败', icon: 'none' });
							}
						})
					}
				}
			});
		},
		gotoCompleted(){
			// 确认收货
			let that = this
			uni.showModal({
				title: '提示',
				content: '确认收货吗',
				confirmText: '确定',
				cancelText: '取消',
				success: function (res) {
					if (res.confirm) {
						app.globalData.Request.post(app.globalData.ApiConstant.Order.confirmCompleted, 
						{orderId: that.order.id}).then((res)=>{
							if(res.success){
								uni.showToast({ title: '操作成功', icon: 'success' });
								setTimeout(() => {
									that.loadOrderDetail(that.order.id)
								}, 500);
							}else{
								uni.showToast({ title: '操作失败', icon: 'none' });
							}
						})
					}
				}
			});
		},
	}
};
</script>

<style lang="scss" scoped>
.order-detail-page {
	background-color: #f7f8fa;
	min-height: 100vh;
	// padding-bottom 动态计算，由底部占位view承担
}

.card-style {
	background-color: #fff;
	border-radius: 16rpx;
	margin: 20rpx 24rpx 0;
	padding: 24rpx 30rpx;
	box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.03);
}

.header-status {
	background-color: #fff;
	padding: 30rpx 30rpx 20rpx;
	margin-bottom: 20rpx; // 状态区域和下方内容分隔
	.status-line {
		display: flex;
		align-items: center;
		justify-content: space-between; // 如果右侧有图标
		.status-text {
			font-size: 36rpx;
			font-weight: bold;
			color: #303133;
		}
	}
	.countdown-timer, .status-message {
		font-size: 26rpx;
		color: #606266;
		margin-top: 15rpx;
		.time-segment {
			font-weight: bold;
			color: #fa3534; // 红色时间
			margin: 0 4rpx;
		}
	}
}

.address-section {
	display: flex;
	align-items: flex-start; // 地址可能多行
	.location-icon {
		margin-right: 15rpx;
		margin-top: 6rpx; // 微调对齐
		flex-shrink: 0;
	}
	.address-details {
		flex-grow: 1;
        min-width: 0; // 防止内容溢出
		.contact-info {
			margin-bottom: 8rpx;
            display: flex; // 让姓名电话在一行
            flex-wrap: wrap; // 防止溢出
			.name {
				font-size: 30rpx;
				font-weight: 500;
				color: #303133;
				margin-right: 20rpx;
                flex-shrink: 0;
			}
			.phone {
				font-size: 28rpx;
				color: #606266;
                flex-shrink: 0;
			}
		}
		.full-address {
			font-size: 26rpx;
			color: #606266;
			line-height: 1.5;
            word-break: break-all; // 允许在任何字符间断行
		}
	}
	.modify-address-btn {
		background-color: #f5f5f5;
		color: #333;
		border-radius: 30rpx;
		padding: 0 20rpx;
		font-size: 24rpx;
		height: 50rpx;
		line-height: 50rpx;
		margin-left: 20rpx;
		flex-shrink: 0;
		border: none;
		&::after { border: none; }
	}
}

.product-section {
	display: flex;
	align-items: center;
	.product-image {
		width: 120rpx;
		height: 120rpx;
		border-radius: 8rpx;
		margin-right: 20rpx;
		flex-shrink: 0;
		background-color: #f0f0f0;
	}
	.product-info {
		flex-grow: 1;
		margin-right: 20rpx;
		overflow: hidden;
        min-width: 0; // 防止内容溢出
		.product-name {
			font-size: 28rpx;
			color: #333;
			// 多行省略
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 2;
			overflow: hidden;
			text-overflow: ellipsis;
            line-height: 1.4;
		}
	}
	.product-price {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
		flex-shrink: 0;
	}
}

.price-details-section {
	.price-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15rpx 0;
		&:first-child { // 成交价的展开图标特殊处理
			uni-icons {
				margin-left: auto; // 推到价格左边
				margin-right: 10rpx;
			}
		}
		.label {
			font-size: 26rpx;
			color: #606266;
		}
		.value {
			font-size: 26rpx;
			color: #303133;
			&.actual-price {
				font-weight: bold;
				font-size: 30rpx;
				color: #fa3534;
			}
		}
	}
}

.order-info-section, .seller-section {
	.info-item, .seller-details {
		display: flex;
		align-items: center;
		padding: 15rpx 0;
		font-size: 26rpx;
		.label {
			color: #606266;
			width: 180rpx; // 固定标签宽度，方便对齐
			flex-shrink: 0;
		}
		.value {
			color: #303133;
			flex-grow: 1;
			word-break: break-all; // 防止长编号不换行
            min-width: 0; // 防止溢出
			&.placeholder {
				color: #999;
				font-size: 24rpx;
			}
		}
		.copy-btn {
			background-color: #f5f5f5;
			color: #333;
			border-radius: 20rpx;
			padding: 0 15rpx;
			font-size: 22rpx;
			height: 40rpx;
			line-height: 40rpx;
			margin-left: 15rpx;
			border: none;
			flex-shrink: 0; // 防止被挤压
			&::after { border: none; }
		}
		uni-icons[type="right"] {
			margin-left: 10rpx;
            flex-shrink: 0;
		}
	}
	.seller-header {
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
	}
	.seller-details {
		padding-top: 0; // 调整内边距
		.seller-avatar {
			width: 60rpx;
			height: 60rpx;
			border-radius: 50%;
			margin-right: 15rpx;
			flex-shrink: 0;
		}
		.seller-name {
			font-size: 28rpx;
			font-weight: 500;
			color: #333;
			margin-right: 15rpx;
            flex-shrink: 0;
		}
		.seller-credit {
			font-size: 24rpx;
			color: #606266;
            flex-grow: 1; // 占据剩余空间
		}
	}

	.toggle-more-info {
		display: flex;
		align-items: center;
		justify-content: center;
		color: #999;
		font-size: 24rpx;
		padding-top: 20rpx;
		text {
			margin-right: 6rpx;
		}
	}
}

.recommendation-section {
	margin-top: 30rpx;
	padding: 0 24rpx;
	.rec-title {
		display: flex;
		align-items: center;
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
	}
	.rec-placeholder {
		text-align: center;
		color: #ccc;
		padding: 50rpx 0;
		background-color: #fff;
		border-radius: 16rpx;
	}
}

.bottom-actions {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #fff;
	display: flex;
	justify-content: flex-end; // 按钮靠右
	align-items: center;
	padding: 15rpx 24rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
	z-index: 100;
	.action-btn {
		height: 70rpx;
		line-height: 70rpx;
		border-radius: 35rpx;
		font-size: 26rpx;
		padding: 0 30rpx;
		margin-left: 20rpx;
		border: 1rpx solid #ccc;
		background-color: #fff;
		color: #333;
		display: flex;
		align-items: center;
		justify-content: center;
        flex-shrink: 0; // 防止按钮被挤压

		&::after { border: none; }
		&.secondary-btn {
			// 联系卖家这种按钮可以更靠左
			margin-right: auto;
			margin-left: 0;
             border-color: #f0f0f0; // 浅一点的边框
             background-color: #f5f5f5; // 浅一点的背景
		}
		&.primary-btn {
			background-color: #ff5000;
			color: #fff;
			border-color: #ff5000;
            font-weight: bold;
		}
	}
}

// 取消订单抽屉样式
.cancel-drawer-content {
	padding: 30rpx;
	// 底部安全区 padding 由 popup-footer 处理
	background-color: #fff;
	border-top-left-radius: 20rpx;
	border-top-right-radius: 20rpx;

	.drawer-title {
		font-size: 32rpx;
		font-weight: bold;
		text-align: center;
		margin-bottom: 40rpx;
		display: block;
	}
	.reason-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 25rpx 0;
		font-size: 28rpx;
		color: #333;
		&:not(:last-child) {
			border-bottom: 1rpx solid #f5f5f5;
		}
	}
	.drawer-actions {
		display: flex;
		margin-top: 40rpx;
		padding-bottom: constant(safe-area-inset-bottom); /* 适配iPhone X等底部安全区域 */
        padding-bottom: env(safe-area-inset-bottom);
		.drawer-btn {
			flex: 1;
			height: 80rpx;
			line-height: 80rpx;
			border-radius: 40rpx;
			font-size: 28rpx;
			text-align: center;
			&::after { border: none; }
			&.secondary {
				background-color: #f5f5f5;
				color: #333;
				margin-right: 20rpx;
			}
			&.primary {
				background-color: #FFC800; // 闲鱼黄
				color: #333;
				font-weight: bold;
				&:disabled {
					background-color: #f0f0f0;
					color: #aaa;
				}
			}
		}
	}
}

.loading-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(255, 255, 255, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    text {
        font-size: 32rpx;
        color: #666;
    }
}
</style>